// electron / main.ts
import { app, BrowserWindow,ipcMain} from 'electron';
import { join } from 'path';
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
const createWindow = () => {
    const win = new BrowserWindow({
        width: 680,
        height: 430,
        frame: false,//隐藏头部
        resizable: false,//用户是否可以调整窗口大小
        show: false, //先不显示窗口，等窗口准备好了才显示，防止渲染未完成时出现白框
        maximizable: false,//禁止双击最大化
        webPreferences: {
            nodeIntegration: true, // 设置是否在页面中启用 Node.js 集成模式
            contextIsolation: false, // 设置是否启用上下文隔离模式。

        },
    });

    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL);
    } else {
        win.loadFile('index.html')
    }
    const initLoginWindow = (windowObj) => {
        //去登陆页面
        windowObj.setTitle('登录');
        windowObj.setSize(680, 430);
        windowObj.setMinimumSize(680, 430);
        windowObj.setResizable(false);
        windowObj.setMaximizable(false);
        windowObj.center();
    };

    const initMainWindow =  (windowObj) => {
        //去首页
        windowObj.setTitle('首页');
        windowObj.setSize(1400, 900);
        windowObj.setMinimumSize(1400, 900);
        windowObj.setResizable(true);
        windowObj.setMaximizable(true);
        windowObj.center();

    }
    const delayShowWindow = (initFn, delay) => {
        //切换过渡登录界面切换到主界面或者从主界面切换到登陆页面，这时候直接变化大小看起来很奇怪，最好需要做点处理过渡一下
        win.setOpacity(0);
        initFn(win);
        // 在最小化之后修改size会无效，所以要在最小化之前修改大小
        win.minimize();
        setTimeout(() => {
            win.setOpacity(1);
            win.show();
            win.focus();
        }, delay);
    }
    win.on('ready-to-show', () => {
        win.show() // 初始化后再显示
    })
    ipcMain.on('window-close', () => {
        win.close()//关闭窗口
    });
    ipcMain.on('window-max', function() {
        //最大化
        if (win.isMaximized()) {
            win.restore();
        } else {
            win.maximize();
        }
    });
    ipcMain.on('window-min', function() {
        //最小化
        win.minimize();
    })
    ipcMain.on('showMainWindow', (event, delay=500) => {
        if (delay) {
            delayShowWindow(initMainWindow, delay);
        } else {
            initMainWindow(win);
        }
    });
    ipcMain.on('showLoginWindow', (event, delay=500) => {
        console.log(delay);
        if (delay) {
            delayShowWindow(initLoginWindow, delay);
        } else {
            initLoginWindow(win);
        }
    });
};

app.whenReady().then(createWindow);
